//
//  MineViewController.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/11.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "MineViewController.h"
#import "LDY_HeaderView.h"
#import "MineTableViewCell.h"
#import "LDY_ArticleCollectionViewController.h"
#import "CXSelectSaveViewController.h"
#import <MessageUI/MessageUI.h>
#define WIDTH self.view.frame.size.width
#define HEIGHT 180

@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) LDY_HeaderView *headerView;

@property (nonatomic, retain) NSArray *titleArr;

@property (nonatomic, retain) NSArray *picNameArr;

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleArr = @[@"我的音乐", @"我的文章", @"清除缓存", @"关于我们", @"意见反馈"];
    
    self.picNameArr = @[@"music", @"book", @"qingchu", @"about", @"xinfeng"];
    
    [self createTableView];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.headerView = [[LDY_HeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.headerView.headerView.image = [UIImage imageNamed:@"1024768"];
    
    self.tableView.tableHeaderView = self.headerView;
    
    [self.headerView release];
    [self.tableView release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        LDY_ArticleCollectionViewController *articleCollection = [[LDY_ArticleCollectionViewController alloc] init];
        
        [self.navigationController pushViewController:articleCollection animated:YES];
        
        [articleCollection release];
    }
    if (indexPath.row == 0) {
        CXSelectSaveViewController *saveMusic = [[CXSelectSaveViewController alloc] init];
        
        saveMusic.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:saveMusic animated:YES];
    }
    if (indexPath.row == 4) {
        if (![MFMailComposeViewController canSendMail]) {
            
        }
        MFMailComposeViewController *MFMailController = [[MFMailComposeViewController alloc]init];
        MFMailController.mailComposeDelegate = self;
        [MFMailController setToRecipients:@[@"18525461598@163.com", @"892108437@qq.com"]];
        
        [MFMailController setMessageBody:@"请给我们您的宝贵意见" isHTML:NO];
        
        [MFMailController setSubject:@""];
        
        
        [self presentViewController:MFMailController animated:YES completion:nil];

    }
    if (indexPath.row == 2) {
#pragma mark 清除缓存
        [self createAlertViewController];
        
    }
}

-(void)createAlertViewController{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@",filePath);
    NSString *cachePath = [NSString stringWithFormat:@"%@/Caches", filePath];
    NSString *string = [NSString stringWithFormat:@"是否确认清除(%.2fM)",[self floatWithPath:cachePath]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string  preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *defautAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self removeCache];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:defautAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)file
{
    
    NSFileManager *cache = [NSFileManager defaultManager];
    if ([cache fileExistsAtPath:file]) {
        return [[cache attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}

// 计算清除的缓存大小
- (CGFloat)floatWithPath:(NSString *)path
{
    CGFloat num = 0;
    NSFileManager *cache = [NSFileManager defaultManager];
    if ([cache fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[cache subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    return num / (1024.0 * 1024.0);
}

// 删除缓存
- (void)removeCache
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@", cachePath);
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *p in files) {
        NSString * path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }
}


#pragma mark 发邮件
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    
    switch (result)
    {
            //用户取消编辑
        case MFMailComposeResultCancelled:
            NSLog(@"Mail send canceled...");
            break;
            //用户保存邮件
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved...");
            break;
            //用户点击发送
        case MFMailComposeResultSent:{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"发送成功!" message:@"感谢您的反馈" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
            break;
            //用户尝试保存或者发送邮件失败
        case MFMailComposeResultFailed:
            NSLog(@"Mail send errored: %@…", [error localizedDescription]);
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineCell"];
    if (!cell) {
        cell = [[MineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MineCell"];
    }
    
    cell.titleLabel.text = [self.titleArr objectAtIndex:indexPath.row];
    
    cell.picImageView.image = [UIImage imageNamed:[self.picNameArr objectAtIndex:indexPath.row]];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView) {
        CGFloat dy = scrollView.contentOffset.y;
//        NSLog(@"%f", dy);
        if (dy < 0) {
            self.headerView.headerView.frame = CGRectMake(-(-(dy) * WIDTH / HEIGHT) / 2, dy, WIDTH - (dy) * WIDTH / HEIGHT, HEIGHT - dy);
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
